function switchMovie(videoFileName) {
    $("#video-src").attr("src", "video/" + videoFileName);
    document.getElementById("video-player").load();
}

function loadMovieListGridFragment(page) {
    var typeId = $("#select-movie-type").val();
    if (typeId === undefined || typeId == null) {
        typeId = 0;
    }
    if (page === undefined) {
        page = 0;
    }
    $("#list-grid-main").load('/movie/list/grid/fragment?page=' + page + '&size=12&typeId=' + typeId);
}

function queryMovieByCondition(page) {
    if (page === undefined) {
        page = 0;
    }
    var condition = $("#form-query-condition").serialize();
    $("#list-grid-main").load("/movie/query/condition?" + condition + "&page=" + page + "&size=12");
}

function loadPersonListGridFragment(page) {
    if (page === undefined) {
        page = 0;
    }
    $("#person-list-grid-fragment").load('/person/list/grid/fragment?page=' + page + '&size=9');
}

function loadNewsList(page) {
    if (page === undefined) {
        page = 0;
    }
    $("#movie-news-list-fragment").load('/movie/news/list/fragment?page=' + page);
}


/**
 * 退出登录
 */
function logout() {
    $.get("/admin/logout", function (msg) {
        if (msg === "true") {
            window.location = "/";
        } else {
            alert("退出异常!");
        }
    });
}

function initLoginForm() {
    //==js for login and sign up
    var loginLink = $(".loginLink");
    var signupLink = $(".signupLink");
    var loginct = $("#login-content");
    var signupct = $("#signup-content");
    var loginWrap = $(".login-wrapper");
    var overlay = $(".overlay");
    loginWrap.each(function () {
        $(this).wrap('<div class="overlay"></div>')
    });
    //pop up for login form
    loginLink.on('click', function (event) {
        event.preventDefault();
        loginct.parents(overlay).addClass("openform");
        $(document).on('click', function (e) {
            var target = $(e.target);
            if ($(target).hasClass("overlay")) {
                $(target).find(loginct).each(function () {
                    $(this).removeClass("openform");
                });
                setTimeout(function () {
                    $(target).removeClass("openform");
                }, 350);
            }
        });
    });
    //pop up for signup form
    signupLink.on('click', function (event) {
        event.preventDefault();
        signupct.parents(overlay).addClass("openform");
        $(document).on('click', function (e) {
            var target = $(e.target);
            if ($(target).hasClass("overlay")) {
                $(target).find(signupct).each(function () {
                    $(this).removeClass("openform");
                });
                setTimeout(function () {
                    $(target).removeClass("openform");
                }, 350);
            }
        });
    });
    // close popup for mobile
    var closebt = $(".close");
    closebt.on('click', function (e) {
        e.preventDefault();
        var overlay = $(".overlay");
        overlay.removeClass("openform");
    });
}

function saveUser() {
    var data = $("#user-form").serialize();
    $.ajax({
        url: "/user/update",
        type: "PUT",
        data: data,
        success: function (result) {
            if (result) {
                alert("保存成功");
            } else {
                alert("保存失败");
            }
        },
        error: function () {
            alert("数据异常,请检查你输入的数据");
        }
    });
}

function changeUserPwd() {
    var oldPwd = $("#oldPassword").val();
    var newPwd = $("#newPassword1").val();
    var newPwd2 = $("#newPassword2").val();
    if (oldPwd === undefined || newPwd === undefined || newPwd2 === undefined
        || oldPwd.length === 0 || newPwd.length === 0 || newPwd2.length === 0) {
        alert("密码不能为空")
        return;
    }
    if (oldPwd === newPwd) {
        alert("新密码和旧密码不能一样");
        return;
    }
    if (newPwd !== newPwd2) {
        alert("两次输入的密码必须一致");
        return;
    }
    var data = $("#user-pwd-form").serializeArray();
    data.push({name: "oldPassword", value: hex_md5(oldPwd)});
    data.push({name: "newPassword", value: hex_md5(newPwd)});
    $.ajax({
        url: "/user/changePwd",
        type: "PUT",
        data: data,
        success: function (result) {
            if (result) {
                alert("修改成功");
            } else {
                alert("修改密码失败,请检查你输入的密码是否正确.");
            }
        },
        error: function () {
            alert("数据异常,请检查你输入的数据");
        }
    });
}

function register() {
    var pwd = $("#newPassword1").val();
    var pwd2 = $("#newPassword2").val();
    if (pwd === undefined || pwd2 === undefined || pwd.length === 0 || pwd2.length === 0) {
        alert("密码不能为空")
        return;
    }
    if (pwd !== pwd2) {
        alert("两次输入的密码必须一致");
        return;
    }
    var data = $("#user-pwd-form").serializeArray();
    data.push({name: "password", value: hex_md5(pwd)});
    $.ajax({
        url: "/user/register",
        type: "POST",
        data: data,
        success: function (result) {
            if (result) {
                alert("注册成功");
            } else {
                alert("注册失败.");
            }
        },
        error: function () {
            alert("数据异常,请检查你输入的数据");
        }
    });
    return false;
}

/**
 * 注册用户
 */
function registerUser() {
    if (!checkUserAccountIsExist()) {
        var data = $("#register-user-form").serializeArray();
        var password = $("#reg-password").val();
        var rePassword = $("#reg-re-password").val();
        if (password !== rePassword) {
            alert("两次密码不一致,请重新输入");
            return;
        }
        password = hex_md5(password);
        data.push({name: "password", value: password});
        $.ajax({
            type: "POST",
            url: "/user/save",
            data: data,
            async: false,
            success: function (result) {
                if (result) {
                    var account = $("#account").val();
                    alert("注册成功");
                    var formData = new FormData();
                    formData.append("username", account);
                    formData.append("password", password);
                    formData.append("remember-me", "true");
                    login(formData, "user");
                } else {
                    alert("注册失败");
                }
            }
        });

    }
}

/**
 * 判断帐号是否存在
 */
function checkUserAccountIsExist() {
    var id = $("#userId").val();
    if (id === undefined) {
        id = 0;
    }
    var account = $("#account").val();
    var url = "/user/exist?account=" + account + "&id=" + id;
    var isExist = false;
    $.ajax({
        url: url,
        async: false,
        success: function (result) {
            if (result) {
                alert("帐号已存在")
            }
            isExist = result;
        }
    });
    return isExist;
}

var starLock = -1;

function initRateStar(count) {
    var div = $("#star");
    for (var i = 0; i < count; i++) {
        var star = $("<img src='/movie/images/star1.png'>").attr("index", i);
        star.hover(function () {
            starLock = -1;
            setStarOut();
            var rate = parseInt(this.attributes.index.value) + 1;
            setStarOver(rate);
        }, function () {
            setStarOut();
        }).click(function () {
            starLock = parseInt(this.attributes.index.value);
            $("#rate").val(starLock);
        });
        div.append(star);
    }
}

function setStarOver(count) {
    var stars = $("#star img");
    for (var i = 0; i < count; i++) {
        stars.eq(i).attr("src", "/movie/images/star2.png");
    }
}

function setStarOut() {
    if (starLock !== -1) {
        return;
    }
    var stars = $("#star img");
    for (var i = 0; i < stars.length; i++) {
        stars.eq(i).attr("src", "/movie/images/star1.png");
    }
    starLock = -1;
}

function showRateWindow() {
    initRateStar(10);
    var content = $("#star").removeAttr("hidden");
    $.Pop(content[0], 'alert', function () {
        var rate = parseInt($("#rate").val()) + 1;
        var id = $("#movie-id").val();
        $.ajax({
            url: "/movie/rate",
            type: "GET",
            data: "rate=" + rate + "&id=" + id,
            success: function (result) {
                try {
                    if (result === true) {
                        alert("评分成功,你打了" + rate + "分");
                    } else {
                        alert("评分失败");
                    }
                } catch (e) {
                    alert("评分失败");
                } finally {
                    $("#generator-star").append($("<div id='star' hidden='hidden'>"));
                }
            }
        });
    });
}

function favoriteMovie() {
    var id = $("#movie-id").val();
    if (isNaN(id)) {
        return;
    }
    var isFavorite = Boolean($("#movie-favorite").attr("isFavorite") === "true");
    $.ajax({
        url: "/user/favorite?movieId=" + id + "&isFavorite=" + !isFavorite,
        type: "GET",
        success: function (result) {
            var message = result.msg;
            if (message === undefined) {
                alert("收藏失败");
                return;
            }
            alert(message);
            if (result.success === true) {
                $("#movie-favorite").attr("isFavorite", !isFavorite);
                if (isFavorite) {
                    $("#span-favorite").text("标记为喜欢");
                } else {
                    $("#span-favorite").text("取消喜欢");
                }
            }
        },
        error: function (errorMsg) {
            console.log(errorMsg);
        }
    });
}
